
//
//  HRWebService.m
//  haierapp
//
//  Created by Xia Zhiyong on 14-8-21.
//  Copyright (c) 2014年 haier. All rights reserved.
//

#import "HRWebService.h"
#import "HRServerAction.h"
#import <AFHTTPRequestOperation.h>


@implementation HRWebService


+(void)startRequest:(NSString *)action body:(NSString *)body returnClass:(Class)returnClass success:(RequestSuccessBlock)sBlock failure:(RequestFailureBlock)fBlock{
    
    NSString *server = [[HRServerAction shareInstance] objectForKey:action];

    NSString *serverUrl = [NSString stringWithFormat:@"%@/%@/%@",kBaseUrl,server,action];
//#ifdef forTest
//    serverUrl = [NSString stringWithFormat:@"%@/%@/%@",kBaseUrl,server,action];
//#else
//    if (body) {
//        serverUrl = [NSString stringWithFormat:@"%@/%@/%@",kBaseUrl,server,action];
//    }else{
//         serverUrl = [NSString stringWithFormat:@"%@/%@/%@",kBaseUrl,server,action];
//    }
//#endif


    NSLog(@">>>>>>>>serverUrl:%@",[NSString stringWithFormat:@"%@/%@/%@?result=%@",kBaseUrl,server,action,body]);
    
    NSDictionary *paramDic=nil;
    
    if (body!=nil && ![body isEqualToString:@""]) {
        paramDic=[NSDictionary dictionaryWithObjectsAndKeys:body,@"result", nil];
    }
    
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    [manager GET:serverUrl parameters:paramDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        //请求成功
        NSString *responseStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSError *err = nil;
        HRResultModel *result = [HRWebService getResultWithString:responseStr returnClass:returnClass andError:&err];
        if (err)
        {
            // 数据解析错误，出现该错误说明与服务器接口对应出了问题
            
            if (fBlock)
            {
                fBlock(nil, err);
            }
            
        }
        else
        {
            if (sBlock)
            {
                sBlock(operation, result);
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        fBlock(nil,error);
    }];

}



// 从字符串转换成ResultModel
+ (HRResultModel *)getResultWithString:(NSString *)responseObj returnClass:(Class)returnClass andError:(NSError**)err
{
    
    @try {
//        RespondModel *aRespond = [[RespondModel alloc] initWithString:aString error:nil];
//        aString = [aString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        NSDictionary *body=[responseObj toArrayOrDictionary];
        NSLog(@">>>>%@",body);
        HRResultModel *result = [[HRResultModel alloc] init];
        result.code = [[body objectForKey:@"code"] intValue];
        result.desc = [NSString stringWithString:[body objectForKey:@"desc"]];
        // 如果状态码不为0,则直接返回,不再解析后面的数据
        if (result.code != 0)
        {
            result.content = nil;
            return result;
        }
        if (returnClass == nil) {
            result.content = [body objectForKey:@"content"];
            return result;
        }
        // 判断返回数据是否正常,先判断code和message即可
        if ([[body objectForKey:@"content"] isKindOfClass:[NSDictionary class]])
        {   // result返回字典类型数据
            if ([body objectForKey:@"content"] && returnClass)
            {
                result.content = [[returnClass alloc] initWithDictionary:[body objectForKey:@"content"] error:err];
            }
        }
        else if ([[body objectForKey:@"content"] isKindOfClass:[NSString class]])
        { // result返回字串类型数据
        
            if ([body objectForKey:@"content"] == nil || [[body objectForKey:@"content"] isEqualToString:@""] == YES)
            {
                result.content = nil;
            } else {
                result.content = [body objectForKey:@"content"];
            }
        }else if ([[body objectForKey:@"content"] isKindOfClass:[NSNumber class]])
        {
        
            if ([body objectForKey:@"content"] == nil)
            {
                result.content = nil;
            } else {
                result.content = [body objectForKey:@"content"];
            }
        }
        else if ([[body objectForKey:@"content"] isKindOfClass:[NSArray class]])
        {  // result返回数组类型数据
    
            if ([body objectForKey:@"content"] && returnClass)
            {
                NSArray *array = [body objectForKey:@"content"];
                if (array != nil && array.count > 0)
                {
                    NSMutableArray *resultArr = [[NSMutableArray alloc] init];
                    for (int i = 0; i < array.count; i++)
                    {
                        NSDictionary *dic = [array objectAtIndex:i];
                        [resultArr addObject:[[returnClass alloc] initWithDictionary:dic error:err]];
                    }   // for
                    result.content = resultArr;
                }
                else
                {
                    result.content = nil;
                }
            }
        }
        return result;
    }
    @catch (NSException *exception)
    {
    
        *err = [[NSError alloc] initWithDomain:exception.reason code:-500 userInfo:exception.userInfo];
        return nil;
    }
    @finally {
        //
    }
    
}


@end
